package com.longrise.android.byjk.plugins.vip.integralexchange;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.longrise.android.byjk.R;
import com.longrise.common.base.BaseFragment;
import com.longrise.android.byjk.common.Control;
import com.longrise.android.byjk.event.IntegralTaskEvent;
import com.longrise.common.utils.NetUtil;
import com.longrise.android.byjk.utils.Tracker_Google;
import com.longrise.android.byjk.widget.view.BaseFrameView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by callxkj on 2017/8/1.
 * 积分任务
 */

public class IntegralTaskFragment extends BaseFragment implements BaseFrameView.ReloadListener, View.OnClickListener {


    private static final String TAG = "IntegralTaskFragment";
    public static String URL = "url"; //webview加载链接
    private BaseFrameView mBfv;
    private WebView mWv;
    private WebSettings webSettings;
    private boolean mLoadError = false;
    private boolean mIsCurrentPage = true;
    private String mUrl;
    private String mFirstUrl;
    private RelativeLayout mRl1;
    private TextView mTv1;
    private ImageView mIv1;
    public static String CURRENT_PAGE = "current_page";
    public static String DAILY_TASK = "daily_task";
    public static String BASIC_TASK = "basic_task";
    private String mCurrentPage = BASIC_TASK;

    @Override
    protected int getLayoutResourse(@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_integraltask;
    }

    @Override
    public void initView() {
        mBfv = (BaseFrameView) mRootView.findViewById(R.id.fragment_integraltask_bfv);
        mWv = (WebView) mRootView.findViewById(R.id.fragment_integraltask_wv);
        mRl1 = (RelativeLayout) mRootView.findViewById(R.id.fragment_integraltask_rl1);
        mTv1 = (TextView) mRootView.findViewById(R.id.fragment_integraltask_tv1);
        mIv1 = (ImageView) mRootView.findViewById(R.id.fragment_integraltask_iv1);
        initWebView();
        initData();
        initEvent();
        EventBus.getDefault().register(this);
        if (BASIC_TASK.equals(mCurrentPage)) {
            addScreenName("基本任务");
        } else {
            addScreenName("每日任务");
        }

    }

    /**
     * 初始化webview
     */
    private void initWebView() {
        webSettings = mWv.getSettings();
        mWv.clearHistory();
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setUseWideViewPort(true);
        // 设置WebView属性，能够执行Javascript脚本
        webSettings.setJavaScriptEnabled(true);
        //设置 缓存模式 不用缓存 使用localStorage
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSettings.setDomStorageEnabled(true);
        webSettings.setAppCacheMaxSize(1024 * 1024 * 8);
        String absolutePath = mContext.getApplicationContext().getCacheDir().getAbsolutePath();
        webSettings.setAppCachePath(absolutePath);
        webSettings.setAllowFileAccess(true);
        webSettings.setAppCacheEnabled(true);
        webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        mWv.setWebViewClient(new PublicWebClient());
        mWv.setWebChromeClient(new PublicWebChromeClient());
//        mWv.addJavascriptInterface(new BBWebBridge((BaseWebActivity) getActivity(), mRxmanager, mWv), "bb"); //交互放到presenter
    }

    private void initEvent() {
        mBfv.setOnReloadListener(this);
        mIv1.setOnClickListener(this);
    }

    private void initData() {
        mFirstUrl = getArguments().getString(URL);
        mCurrentPage = getArguments().getString(CURRENT_PAGE);
        mUrl = mFirstUrl;
        toLoadUrl(mFirstUrl);
    }

    /**
     * 加载网页
     */
    private void toLoadUrl(String url) {
        if (checkNetwork() && mWv != null) {
            mWv.loadUrl(url);
        }
    }

    /**
     * 检查是否有网络
     *
     * @return
     */
    private boolean checkNetwork() {
        if (!NetUtil.checkNetEnable()) {
            loadError();
            return false;
        } else {
            return true;
        }
    }

    /**
     * 加载失败
     */
    private void loadError() {
        if (mIsCurrentPage) {
            mBfv.setLoadingStatus(BaseFrameView.LoadingStatus.ERROR);
            mBfv.setVisibility(View.VISIBLE);
            mWv.setVisibility(View.GONE);
            mLoadError = true;
        }
    }


    /**
     * 加载失败后 点击屏幕重新加载
     */
    @Override
    public void onReload(View v) {
        mLoadError = false;
        toLoadUrl(mUrl);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.fragment_integraltask_iv1:
                mRl1.setVisibility(View.GONE);
                Control.setIsShowDailyTaskTips(false);
                addGoogleEvent("每日任务提示", "关闭", null);
                break;
        }
    }


    private class PublicWebClient extends WebViewClient {

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
            mLoadError = true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            loadStart();
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            mUrl = url;
            if (mLoadError) {
                loadError();
            } else {
                loadSuccess();
                initBtmTips();
            }
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    }

    private class PublicWebChromeClient extends WebChromeClient {

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            if ((!TextUtils.isEmpty(title)) && title.toLowerCase().contains("error")) {
                mLoadError = true;
            }
        }

        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            return super.onJsAlert(view, url, message, result);
        }
    }


    /**
     * 开始加载
     */
    private void loadStart() {
        if (mIsCurrentPage) {
            mBfv.setLoadingStatus(BaseFrameView.LoadingStatus.LOADING);
            mBfv.setVisibility(View.VISIBLE);
            mWv.setVisibility(View.GONE);
        }
    }


    /**
     * 加载成功
     */
    private void loadSuccess() {
        Disposable subscribe = Observable.timer(200, TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        mBfv.setLoadingStatus(BaseFrameView.LoadingStatus.SUCCESS);
                        mBfv.setVisibility(View.GONE);
                        if (mWv != null) {
                            mWv.setVisibility(View.VISIBLE);
                        }
                        mLoadError = false;
                    }
                });
        mRxmanager.addDisposable(subscribe);
    }


    /**
     * 初始化底部提示栏
     */
    private void initBtmTips() {
        boolean isShowzxyxzTips = Control.getIsShowDailyTaskTips();
        if (isShowzxyxzTips && DAILY_TASK.equals(mCurrentPage)) {
            mRl1.setVisibility(View.VISIBLE);
            //------ 初始化iv ---------------------------------------
            String s1 = "<font color = #FFFFFF>每日任务仅限每日首次，每日可领</font>";
            String s2 = "<font color = #FFA200>1</font>";
            String s3 = "<font color = #FFFFFF>次</font>";
            String s6 = s1 + s2 + s3;
            mTv1.setText(Html.fromHtml(s6));
        }
    }

    /**
     * 刷新积分
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void toHandleIntegralTaskEvent(IntegralTaskEvent event) {
        boolean refresh = event.isRefresh();
        if (refresh) {
            loadStart();
            toLoadUrl(mFirstUrl); // 刷新积分任务
        }
    }

    private void addScreenName(String name) {
        Tracker_Google.getInstance().addGoogleScreenName(name);
    }

    private void addGoogleEvent(String par1, String par2, String par3) {
        Tracker_Google.getInstance().addEvent(par1, par2, par3);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
